##################################################################################################################################
#
# Copyright (C) 2008-2012 Mind System Connection. Lda. Part of Daidze Software, created by Siqsuruq. All other rights reserved.
#
# Mind System Connection Webpage: www.msysc.org
# Daidze Software Page: www.daidze.com www.daidze.org
# E-mail: admin@msysc.org, siqsuruq@gmail.com
#
##################################################################################################################################

proc login {} {
	set w .
	wm title $w [::msgcat::mc "Login"]
	wm geometry $w 320x150
	wm minsize $w 320 150
	wm iconname $w [::msgcat::mc "Login"]
	pack [set main [ttk::frame .main]]
	set ::daidze_login [xml_wrapper new]
	$::daidze_login load_main base login.xml $main 1
}

proc user_login {} {
	set login_data [$::daidze_login get_values]

	set query "SELECT id FROM \"daidze_user\" WHERE name = \'[dict get $login_data username]\' AND \"password\" = \'[md5::md5 -hex \"[dict get $login_data password]\"]\'"
	set result [$::db execute_query $query]
	if {$result != ""} {
		# Destroing login class, main frame and creating navigation and main classes 
		$::daidze_login destroy
		set ::daidze_nav [xml_wrapper new]
		set ::daidze_main [xml_wrapper new]
		destroy .main

		set ::w .
		# Resize the main window to be bigger
		wm geometry $::w 1024x650
		wm minsize $::w 1024 650
		set software_title "[::msgcat::mc "Daidze Software Version:"] $::daidze_version [::msgcat::mc "Company:"] $::clientunique_id"
		wm iconname $::w [::msgcat::mc "Daidze Software"]
		pack [set ::navmenu [ttk::frame .navmenu]] -padx 2 -pady 2 -fill y -side left -anchor ne
		pack [set ::main [ttk::frame .main]] -fill both -padx 2 -pady 2 -expand yes -side left -anchor ne
		
		set daidze_users::name [dict get $login_data username]
		get_user_group $result
		audit::audit login 3 "User $daidze_users::name login successful"

		if {[dict get $login_data panel] != "0" &&  [lsearch -all [get_user_group $result] admin] != ""} {
			wm title $::w $software_title
			$::daidze_nav load_main base admin_nav.xml $::navmenu 1
			$::daidze_main load_main $::adimin_module $::admin_form $::main 1

		} else {
			wm title $::w $software_title
			$::daidze_nav load_main base nav.xml $::navmenu 1
			$::daidze_main load_main $::user_module $::user_form $::main 1
		}

# Registering user email and email login information
		register_user_email
	} else {
		audit::audit login 3 "User [dict get $login_data username] has no permission to login"
	}
}

proc get_user_group {user_id} {
	set query "SELECT daidze_user_level.\"name\" as daidze_user_level_name FROM daidze_user_permission ,daidze_user , daidze_user_level \
	WHERE daidze_user_permission.fk_daidze_user = daidze_user.id AND daidze_user_permission.fk_daidze_user_level = daidze_user_level.id AND fk_daidze_user = \'$user_id\'"
	set daidze_users::groups [$::db execute_query $query]
}
